package org.patto.main.api.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.patto.common.core.api.BaseApiService;
import org.patto.common.core.api.BaseResponse;
import org.patto.main.api.RegisterService;
import org.patto.main.api.impl.entity.SysUser;
import org.patto.main.api.impl.mapper.SysUserId;
import org.patto.main.api.impl.mapper.SysUserIdMapper;
import org.patto.main.api.impl.mapper.SysUserMapper;
import org.patto.common.core.utils.MD5Utils;
import org.patto.main.utils.SaltUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author songchuanfu
 * @ClassName RegisterServiceImpl
 * @qq 18050164315
 * @addres 1802284273@qq.com
 * @微信: wx-suagcf
 */
@RestController
public class RegisterServiceImpl extends BaseApiService<String> implements RegisterService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserIdMapper sysUserIdMapper;

    /**
     * 为什么
     * java反射机制 获取 当前实现类和接口上是否有加上  @PostMapping("register")
     *
     * @param phoneNumber
     * @param password
     * @return
     */
    @Override
    public BaseResponse<String> register(String phoneNumber, String password) {
        // 1.验证参数是否为空
        if (StringUtils.isEmpty(phoneNumber)) {
            return setResultError("phoneNumber is null");
        }
        if (StringUtils.isEmpty(password)) {
            return setResultError("password is null");
        }
        // 2. 先根据手机号码 查询数据库是否存在该用户 如果不存在才可以注册  如果存在就无法注册
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("phone_number", phoneNumber);
        SysUser sysUser = sysUserMapper.selectOne(sysUserQueryWrapper);
        if (sysUser != null) {
            return setResultError("该手机号码已经存在!");
        }
        // 对密码加密
        String salt = SaltUtils.getSalt();
        String md5Password = MD5Utils.md5(password + salt);
        sysUser = new SysUser(phoneNumber, md5Password, salt);
        // 利用临时表获取用户全部userid
        SysUserId sysUserId = new SysUserId();
        int insert = sysUserIdMapper.getUserId(sysUserId);
        if (insert <= 0) {
            return setResultError();
        }
        sysUser.setId(sysUserId.getUserId());
        int result = sysUserMapper.insert(sysUser);
        return setResultDb(result);
    }

}
